<?php
/**
 * Created by PhpStorm.
 * User: the
 * Date: 2019/3/25
 * Time: 14:02
 */
namespace App\Base;

use App\Router\Router;
use FastRoute\Dispatcher;
use FastRoute\RouteCollector;
use function FastRoute\simpleDispatcher;

class Server
{

    public static function run($request, $response)
    {
        $server     = $request->server;
        $method     = strtoupper($server['request_method']);

        $content = self::url($method, $server['path_info']);
        $response->end($content);
    }

    public static function url($method, $pathUrl)
    {
        $dispatcher = simpleDispatcher(function(RouteCollector $r) {
            $router = Router::url();
            foreach ($router as $k => $v){
                $r->addRoute($v[0], $k, $v[1]);
            }
        });

        if (false !== $pos = strpos($pathUrl, '?')) {
            $pathUrl = substr($pathUrl, 0, $pos);
        }
        $pathUrl = rawurldecode($pathUrl);

        $routeInfo = $dispatcher->dispatch($method, $pathUrl);
        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                return '没有找到路由';
                break;
            case Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                return '请求方式不允许';
                break;
            case Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];
                $action = explode('@', $handler);
                if (!class_exists($action[0])){
                    return '控制器不存在';
                }

                $controller = new $action[0];
                $ret = call_user_func(array($controller, "index"), $vars);
                if (is_array($ret)){
                    $resData = json_encode($ret);
                }else{
                    $resData = $ret;
                }
                
                return $resData;

                break;
        }
    }

    public function match($action)
    {

    }
}